package com.whacos.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.whacos.common.annotations.Log;
import com.whacos.common.controller.BaseController;
import com.whacos.common.entity.Tree;
import com.whacos.common.enums.Constant;
import com.whacos.common.utils.BeanUtils;
import com.whacos.common.utils.ObjectUtils;
import com.whacos.common.utils.StringUtils;
import com.whacos.common.vo.ResponseVO;
import com.whacos.modules.system.entity.SysDept;
import com.whacos.modules.system.service.SysDeptService;
import com.whacos.modules.system.vo.SysDeptVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiongdun
 * @description SysDeptController
 * @since 2018/11/17 17:11
 */
@Controller
@RequestMapping("/sys/dept")
@Slf4j
public class SysDeptController extends BaseController {

    private static final String PREFIX = "sys/dept";
    @Autowired
    private SysDeptService sysDeptService;

    // @Log(value = "跳转到修改部门")
    @GetMapping()
    @RequiresPermissions("sys:dept:dept")
    public String dept() {
        return PREFIX + "/dept";
    }

    // @Log(value = "跳转到修改部门")
    @GetMapping("/list")
    @ResponseBody
    @RequiresPermissions("sys:dept:dept")
    public List<SysDeptVO> list(SysDeptVO sysDeptVO) {
        List<SysDeptVO> sysDeptVOList = new ArrayList<>();
        try {
            // 转换请求参数对象
            // 查询部门信息
            List<SysDept> sysDeptList = sysDeptService.list(Wrappers.lambdaQuery(new SysDept())
                    .eq(StringUtils.isNotEmpty(sysDeptVO.getName()), SysDept::getDeptName, sysDeptVO.getName())
                    .eq(StringUtils.isNotEmpty(sysDeptVO.getEmail()), SysDept::getDeptEmail, sysDeptVO.getEmail())
                    .eq(ObjectUtils.isNotEmpty(sysDeptVO.getLeaderId()), SysDept::getLeaderId, sysDeptVO.getLeaderId())
                    .eq(ObjectUtils.isNotEmpty(sysDeptVO.getStatus()), SysDept::getStatus, sysDeptVO.getStatus())
                    .orderByAsc(SysDept::getOrderNum));
            // 转换返回对象结果
            sysDeptList.forEach(sysDeptReturn -> {
                SysDeptVO sysDeptVOReturn = new SysDeptVO();
                BeanUtils.copyProperties(sysDeptReturn, sysDeptVOReturn);
                sysDeptVOList.add(sysDeptVOReturn);
            });
        } catch (Exception e) {
            log.error("查询部门信息列表异常，异常原因：" + e.getMessage(), e);
        }
        return sysDeptVOList;
    }

    // @Log(value = "跳转到修改部门")
    @GetMapping("/add/{parentId}")
    @RequiresPermissions("sys:dept:add")
    public String add(@PathVariable("parentId") Long parentId, Model model) {
        model.addAttribute("parentId", parentId);
        if (ObjectUtils.isEmpty(parentId) || parentId == 0) {
            model.addAttribute("parentDeptName", "总部门");
        } else {
            model.addAttribute("parentDeptName", sysDeptService.getById(parentId).getDeptName());
        }
        return PREFIX + "/add";
    }

    // @Log(value = "跳转到修改部门")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("sys:dept:edit")
    public String edit(@PathVariable("id") Long id, Model model) {
        try {
            SysDept sysDept = sysDeptService.getById(id);
            model.addAttribute("sysDept", sysDept);
            if (Constant.DEPT_ROOT_ID.equals(sysDept.getParentId())) {
                model.addAttribute("parentDeptName", "无");
            } else {
                SysDept parentDept = sysDeptService.getById(sysDept.getParentId());
                model.addAttribute("parentDeptName", parentDept.getDeptName());
            }
        } catch (Exception e) {
            return "error";
        }
        return PREFIX + "/edit";
    }

    @Log(value = "保存部门信息")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("sys:dept:add")
    public ResponseVO save(SysDeptVO sysDeptVO) {
        try {
            if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
                return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
            }
            // 请求参数
            SysDept sysDept = new SysDept();
            BeanUtils.copyProperties(sysDeptVO, sysDept);

            // 新增表记录
            sysDept.createdData(this.getUserId());
            if (sysDeptService.save(sysDept)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            log.error("保存部门信息异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    @Log(value = "修改部门信息")
    @ResponseBody
    @PostMapping("/update")
    @RequiresPermissions("sys:dept:edit")
    public ResponseVO update(SysDeptVO sysDeptVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            // 请求参数
            SysDept sysDept = new SysDept();
            BeanUtils.copyProperties(sysDeptVO, sysDept);

            sysDept.updatedData(this.getUserId());
            if (sysDeptService.updateById(sysDept)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            log.error("修改部门信息异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    @Log(value = "删除部门信息")
    @ResponseBody
    @PostMapping("/remove")
    @RequiresPermissions("sys:dept:remove")
    public ResponseVO remove(@RequestParam(value = "id") Long id) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            // 查询 parentId 为当前选中id的部门数，如果不为0 则表示存在子部门，不能被直接删除
            if (sysDeptService.count(new LambdaQueryWrapper<SysDept>()
                    .eq(SysDept::getParentId, id)) > 0) {
                return ResponseVO.error(ResponseVO.ERROR_CODE, "包含下级部门,不允许修改");
            }
            if (sysDeptService.checkDeptHasUser(id)) {
                if (sysDeptService.removeById(id)) {
                    return ResponseVO.success();
                }
            } else {
                return ResponseVO.error(ResponseVO.ERROR_CODE, "部门包含用户,不允许修改");
            }
        } catch (Exception e) {
            log.error("删除部门信息异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    @Log(value = "批量删除部门信息")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("sys:dept:batchRemove")
    public ResponseVO batchRemove(@RequestParam("ids[]") List<Long> ids) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            if (sysDeptService.removeByIds(ids)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            log.error("批量删除部门信息异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    // @Log(value = "跳转到修改部门")
    @GetMapping("/tree")
    @ResponseBody
    public Tree<SysDept> tree() {
        return this.sysDeptService.getTree();
    }

    // @Log(value = "跳转到修改部门")
    @GetMapping("/treeView")
    public String treeView() {
        return PREFIX + "/deptTree";
    }

}
